<template>
  <j-modal
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :title="title"
    :visible="visible"
    :width="700"
    switchFullscreen
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-model
          ref="ruleForm"
          v-bind="formItemLayoutWithOutLabel"
          :model="dynamicValidateForm"
        >
          <a-form-model-item
            v-for="(domain, index) in dynamicValidateForm.domains"
            :key="index"
            v-bind="index === 0 ? formItemLayout : {}"
            :label="index === 0 ? '审批人' : ''"
            style="display: flex;margin-bottom: 10px;"
          >
            <a-form-model-item
              :prop="'domains.' + index + '.value'"
              :rules="{
              required: true,
              message: '审批人不能为空',
              trigger: 'blur',
              }"
              :value="domain.value"
              style="width: 50%; margin-right: 8px;display: inline-block;margin-bottom: 0;"
            >
              <a-select
                :default-active-first-option="false"
                :filter-option="false"
                :not-found-content="null"
                :show-arrow="false"
                placeholder="请输入并选择审批人"
                show-search
                @change="(value) => handlerSearchChange(value, index)"
                @search="handlerSearch"
              >
                <a-select-option v-for="d in searchResult" :key="index" :value="d.id">
                  {{ d.name }}（{{ d.phone }}）
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item
              :prop="'domains.' + index + '.step'"
              :rules="{
              required: true,
              message: '审批人层级不能为空',
              trigger: 'blur',
              }"
              style="width: 39%; margin-right: 8px;display: inline-block;margin-bottom: 0;"
            >
              <a-select :value="domain.step" placeholder="请选择审批层级"
                        @change="(value) => handlerStepChange(value, index)">
                <a-select-option value="1">
                  第一级审批人
                </a-select-option>
                <a-select-option value="2">
                  第二级审批人
                </a-select-option>
              </a-select>
            </a-form-model-item>

            <a-icon
              v-if="dynamicValidateForm.domains.length > 1"
              :disabled="dynamicValidateForm.domains.length === 5"
              class="dynamic-delete-button"
              type="minus-circle-o"
              @click="removeDomain(domain)"
            />
          </a-form-model-item>
          <a-form-model-item v-bind="formItemLayoutWithOutLabel">
            <a-button v-if="dynamicValidateForm.domains.length < 5" style="width: 90%" type="dashed" @click="addDomain">
              <a-icon type="plus"/>
              新增审批人
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'

export default {
  name: 'AgentModel',
  props: {
    getNameList: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      title: '交易信息',
      visible: false,
      model: {},
      searchValue: '',
      saleSource: [],
      searchResult: [],
      SaleInfosLike: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },

      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {},
      url: {
        add: '/sale/cxmSaleProcessConfig/add ',
        edit: '/sale/cxmSaleBaseInfo/editBaseInfo'
      },
      showDing: false,
      showEnterpriseUscc: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 20, offset: 4 }
        }
      },
      dynamicValidateForm: {
        domains: [
          {
            value: undefined,
            step: undefined,
            key: Date.now()
          }
        ]
      }
    }
  },
  created() {
  },
  methods: {
    changeDepositNotes(val) {
      if (val == '不可退') {
        this.showDing = true
      } else {
        this.showDing = false
      }
    },
    add() {
      const that = this
      that.edit({})
    },
    edit(record) {
      console.log(record)
      this.form.resetFields()
      this.model = Object.assign({}, record)
      console.log(this.model)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue({})
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handlerSearchChange(value, index) {
      this.dynamicValidateForm.domains[index].value = value
      // this.dynamicValidateForm.domains[index].step = index + 1
      this.dynamicValidateForm.domains.splice(0, 0)
      setTimeout(() => {
        this.searchResult = []
      }, 200)
    },
    handlerStepChange(value, index) {
      this.dynamicValidateForm.domains[index].step = value
      this.dynamicValidateForm.domains.splice(0, 0)
    },
    handlerSearch(value) {
      // this.searchValue = value
      console.log(value)
      if (value) {
        getAction('/sale/cxmSaleStaffInfo/queryStaff?isConfig=true&name=' + value).then((res) => {
          console.log(res)
          if (res.success) {
            this.searchResult = res.result
            let searchName1 = []
            let searchName2 = []

            // 将已经选择的项目删除
            for (let i in this.searchResult) {
              searchName1.push(this.searchResult[i].id)
            }
            for (let k in this.dynamicValidateForm.domains) {
              searchName2.push(this.dynamicValidateForm.domains[k].value)
            }
            for (let j in searchName2) {
              if (searchName1.indexOf(searchName2[j]) !== -1) {
                this.searchResult.splice(searchName1.indexOf(searchName2[j]), 1)
              }
            }

          }
        })
      } else if (!value) {
        this.searchResult = []
      }
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.$refs.ruleForm.validate(valid => {

        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'post'
          }
          let uploadList = []
          let list = {}
          for (let i in this.dynamicValidateForm.domains) {
            list.handlerId = this.dynamicValidateForm.domains[i].value
            list.step = this.dynamicValidateForm.domains[i].step
            uploadList.push(list)
            list = {}
          }
          console.log(uploadList)
          //时间格式化
          /* formData.createTime = formData.createTime ? formData.createTime.format('YYYY-MM-DD HH:mm:ss') : null */

          httpAction(httpurl, uploadList, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              this.dynamicValidateForm.domains = []
              that.confirmLoading = false
              that.close()
              this.getNameList()
              setTimeout(() => {
                this.addDomain()
              }, 500)
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    removeDomain(item) {
      let index = this.dynamicValidateForm.domains.indexOf(item)
      console.log(index)
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1)
        console.log(this.dynamicValidateForm.domains)
      }
    },
    addDomain() {
      this.dynamicValidateForm.domains.push({
        value: undefined,
        step: undefined,
        key: Date.now()
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>